package edu.hm.vss.producerConsumer;

import java.util.ArrayList;
import java.util.List;

/**
 *
 * @author yasser
 */
public final class Buffer {

    private ArrayList<Object> list;
    private int counter = 0;
    final static int MIN_INDEX = 0;
    final static int MAX_INDEX = 20;
    private boolean stopRequested = false;
    private static Buffer instance;

    private Buffer(int consumers, int producers) {
        list = new ArrayList<Object>(MAX_INDEX);
        for (int i = 0; i < consumers; i++) {
            new Thread(new Consumer(i, this)).start();
        }

        for (int i = 0; i < producers; i++) {
            new Thread(new Producer(i, this)).start();
        }
    }
    
    public synchronized static Buffer getInstance(int consumers, int producers) {
        if (instance == null){
            instance = new Buffer(consumers, producers);
        }
        
        return instance;    
    }

    public List<Object> getList() {
        return list;
    }

    public void add(Object item) {
        list.add(item);
    }

    public Object remove() {
        return list.remove(0);
    }

    public synchronized boolean stopRequested() {
        return stopRequested;
    }

    public synchronized void requestStop() {
        stopRequested = true;
        System.out.println("Stop Requested !");
    }
    
    public int getSize() {
        return counter;
    }

    public void incCounter() {
        counter++;
    }

    public void decCounter() {
        counter--;
    }
}
